import { onMounted,onUnmounted, ref } from 'vue'
import { throttle } from 'underscore'
export default function useScroll(elRef){
  let el = window
  const isReachBottom = ref(false)
  const clientHeight = ref(0)
  const scrollTop = ref(0)
  const scrollHeight = ref(0)
  const scrollListenerHandler = throttle(() => {
    if(el === window){
      clientHeight.value =  document.documentElement.clientHeight
      scrollHeight.value = document.documentElement.scrollHeight
      scrollTop.value = document.documentElement.scrollTop
    }else {
      clientHeight.value = el.clientHeight
      scrollTop.value = el.scrollTop
      scrollHeight.value = el.scrollHeight
    }
    if(clientHeight.value + scrollTop.value >= scrollHeight.value){
      // homeStore.fetchHouselistData()
      isReachBottom.value = true
    }
  }, 100)

  const scrollToTop = () => {
    scrollTop.value = 0
    // scrollTo(x,y) 指定滚动到x轴和y轴位置
    // scrollTo(options) options三个参数：left,top,behavior
    document.documentElement.scrollTo({
      top: 0,
      behavior: "smooth" // 平滑滚动、默认auto瞬间滚动
    })
  }

  const scrollToPosition = (x,y) => {
    document.documentElement.scrollTo(x,y)
  }
  onMounted(()=> {
    if(elRef) {
      el = elRef.value
    }
    el.addEventListener("scroll", scrollListenerHandler)
  })
  onUnmounted(()=>{
    el.removeEventListener("scroll", scrollListenerHandler)
  })
  return { 
    isReachBottom, 
    clientHeight, 
    scrollTop, 
    scrollHeight, 
    scrollToTop,
    scrollToPosition
  }
}